package com.example.security.service;

import com.example.security.DTO.UserDTO;
import com.example.security.entity.Role;
import com.example.security.entity.User;
import com.example.security.entity.UserRole;
import com.example.security.repository.RoleRepository;
import com.example.security.repository.UserRepository;
import com.example.security.repository.UserRoleRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.social.security.SocialUser;
import org.springframework.social.security.SocialUserDetails;
import org.springframework.social.security.SocialUserDetailsService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserService implements UserDetailsService ,SocialUserDetailsService{

    @Autowired
    UserRepository userRepository;
    @Autowired
    UserRoleRepository userRoleRepository;
    @Autowired
    RoleRepository roleRepository;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        System.out.println("查找用户中........");
        User user = userRepository.findUserByUsername(s);
        if (user == null){
            throw new UsernameNotFoundException("用户名不存在");
        }

        UserDTO userDTO = new UserDTO();
        BeanUtils.copyProperties(user,userDTO);
        List<UserRole> userRoleList = userRoleRepository.findUserRoleByUserId(user.getId());
        List<Role> roleList = new ArrayList<>();
        userRoleList.forEach(userRole -> roleList.add(roleRepository.findOne(userRole.getRoleId())));
        userDTO.setRoles(roleList);
        return userDTO;
    }

    @Override
    public SocialUserDetails loadUserByUserId(String userId) throws UsernameNotFoundException {

        //本来这里应该根据这个本地用户唯一标识（userId），
        // 查询本地用户表，返回一个用户对象，由于这里没有绑定本地用户，所以直接返回对象
        System.out.println("qq登录查找用户中。。。");
        return new SocialUser(userId,"",
                true, true,
                true, true,
                AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER"));
    }
}
